package com.sangmo.fts.process.receivable.service;

import com.sangmo.boot.framework.common.utils.DateUtils;
import com.sangmo.boot.framework.data.idm.IdentityManager;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.common.authority.service.AuthorityEntityService;
import com.sangmo.fts.process.receivable.interfaces.RpfRepaymentCreation;
import com.sangmo.fts.process.receivable.model.RpfLoan;
import com.sangmo.fts.process.receivable.model.RpfRepayment;
import com.sangmo.fts.process.receivable.repo.RpfRepaymentRepo;
import com.sangmo.fts.process.storage.model.CsfLoan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class RpfRepaymentEntityService extends AuthorityEntityService<RpfRepayment> {

    @Autowired
    private RpfRepaymentRepo rpfRepaymentRepo;

    @Autowired
    private IdentityManager identityManager;

    @Autowired
    private RpfLoanService rpfLoanService;

    @Override
    protected IDataViewRepo<RpfRepayment> getRepo() {
        return rpfRepaymentRepo;
    }

    @Override
    protected void onCreate(RpfRepayment entity, Object bo) {
        super.onCreate(entity, bo);
        RpfRepaymentCreation creation = (RpfRepaymentCreation) bo;
        entity.setCode(DateUtils.format(new Date(), "yyyyMMdd") + identityManager.next("RPF_REPAYMENT", 4));
        RpfLoan loan = rpfLoanService.get(creation.getLoanId());
        entity.setPayId(loan.getSubDebtor());
        entity.setBankId(loan.getBankId());
        entity.setSellerId(loan.getApplyId());
    }

    @Override
    protected void afterCreated(RpfRepayment entity, Object bo) {
        super.afterCreated(entity, bo);
        List<RpfRepayment> repaymentList = rpfRepaymentRepo.findByLoanId(entity.getLoanId());
        BigDecimal totalPaymentAmount = BigDecimal.ZERO;
        for (RpfRepayment repayment : repaymentList) {
            totalPaymentAmount = totalPaymentAmount.add(repayment.getAmount());
        }
        totalPaymentAmount = totalPaymentAmount.add(entity.getAmount());
        rpfLoanService.settle(entity.getLoanId(), totalPaymentAmount);
    }
}
